package com.tqw.item.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tqw.item.mapper.ItemCatMapper;
import com.tqw.pojo.ItemCat;
import com.tqw.item.service.ItemCatService;
import com.tqw.shipping.feign.ShippingFeignClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Alex
 */
@Slf4j
@Service
public class ItemCatServiceImpl implements ItemCatService {

    @Autowired
    private ItemCatMapper itemCatMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 获取商品分类列表
     * @param level
     * @return
     */
    @Override
    public List<ItemCat> findItemCatList(Integer level) {
        ValueOperations<String, String> vo = redisTemplate.opsForValue();
        ObjectMapper objectMapper = new ObjectMapper();
        Map<Integer,List<ItemCat>> map = getMap();
        if (level == 1){
            String oneCache = vo.get("item:findItemCatList:itemCatOneCache");
            if (oneCache!=null) {
                try {
                    return objectMapper.readValue(oneCache, new TypeReference<List<ItemCat>>(){});
                } catch (JsonProcessingException e) {
                    log.error("com.tqw.item.service.impl.ItemCatServiceImpl.findItemCatList {} caused by redis deserialization exception", e.getMessage());
                }
            }
            List<ItemCat> itemCatList = map.get(0);
            String json = null;
            try {
                json = objectMapper.writeValueAsString(itemCatList);
            } catch (JsonProcessingException e) {
                log.error("com.tqw.item.service.impl.ItemCatServiceImpl.findItemCatList {} caused by redis serialization exception", e.getMessage());
            }
            if (json==null) {
                vo.set("item:findItemCatList:itemCatOneCache", null, Duration.ofSeconds(10));
                return null;
            }
            vo.set("item:findItemCatList:itemCatOneCache", json, Duration.ofMinutes(30));
            return itemCatList;
        }
        if (level == 2){
            String twoCache = vo.get("item:findItemCatList:itemCatTwoCache");
            if (twoCache!=null) {
                try {
                    return objectMapper.readValue(twoCache, new TypeReference<List<ItemCat>>(){});
                } catch (JsonProcessingException e) {
                    log.error("com.tqw.item.service.impl.ItemCatServiceImpl.findItemCatList {} caused by redis deserialization exception", e.getMessage());
                }
            }
            List<ItemCat> twoList = getTwoList(map);
            String json = null;
            try {
                json = objectMapper.writeValueAsString(twoList);
            } catch (JsonProcessingException e) {
                log.error("com.tqw.item.service.impl.ItemCatServiceImpl.findItemCatList {} caused by redis serialization exception", e.getMessage());
            }
            if (json==null) {
                vo.set("item:findItemCatList:itemCatTwoCache", null, Duration.ofSeconds(10));
                return null;
            }
            vo.set("item:findItemCatList:itemCatTwoCache", json, Duration.ofMinutes(30));
            return twoList;
        }
        String threeCache = vo.get("item:findItemCatList:itemCatThreeCache");
        if (threeCache!=null) {
            try {
                return objectMapper.readValue(threeCache, new TypeReference<List<ItemCat>>(){});
            } catch (JsonProcessingException e) {
                log.error("com.tqw.item.service.impl.ItemCatServiceImpl.findItemCatList {} caused by redis deserialization exception", e.getMessage());
            }
        }
        List<ItemCat> threeList = getThreeList(map);
        String json = null;
        try {
            json = objectMapper.writeValueAsString(threeList);
        } catch (JsonProcessingException e) {
            log.error("com.tqw.item.service.impl.ItemCatServiceImpl.findItemCatList {} caused by redis serialization exception", e.getMessage());
        }
        if (json==null) {
            vo.set("item:findItemCatList:itemCatThreeCache", null, Duration.ofSeconds(10));
            return null;
        }
        vo.set("item:findItemCatList:itemCatThreeCache", json, Duration.ofMinutes(30));
        return threeList;
    }

    /**
     * 修改商品分类状态
     * @param itemCat
     */
    @Override
    @Transactional
    public void updateStatus(ItemCat itemCat) {
        itemCatMapper.updateById(itemCat);
    }

    /**
     * 修改商品分类名字
     * @param itemCat
     */
    @Override
    @Transactional
    public void updateItemCat(ItemCat itemCat) {
        itemCatMapper.updateById(itemCat);
    }

    /**
     * 新增商品分类
     * @param itemCat
     */
    @Override
    @Transactional
    public void saveItemCat(ItemCat itemCat) {
        itemCat.setStatus('1'); // '1'代表处于使用状态
        itemCatMapper.insert(itemCat);
    }

    /**
     * 删除商品分类
     * @param itemCat
     */
    @Override
    @Transactional
    public void deleteItemCat(ItemCat itemCat) {
        Integer level = itemCat.getLevel();
        //删除3级
        if (level==3){
            itemCatMapper.deleteById(itemCat.getId());
        }
        //删除2级和3级
        if (level==2){
            Integer parentId = itemCat.getId();
            QueryWrapper<ItemCat> queryWrapper = new QueryWrapper<>();
            //sql:delete from item_cat where parent_id= parentId or id = parentId
            queryWrapper.eq("parent_id", parentId)
                        .or()
                        .eq("id", parentId);
            itemCatMapper.delete(queryWrapper);
        }
        //删除1级,2级,3级
        if (level==1){
            Integer oneId = itemCat.getId();
            QueryWrapper<ItemCat> queryWrapper = new QueryWrapper<>();
            //sql:select id from item_cat where parent_id = oneId
            queryWrapper.eq("parent_id",oneId);
            List twoIds = itemCatMapper.selectObjs(queryWrapper);
            //sql:delete from item_cat where parent_id in (twoIds) or id in (twoIds) or id = oneId
            queryWrapper.clear();
            queryWrapper.in(twoIds!=null&&twoIds.size()>0, "parent_id",twoIds)
                        .or()
                        .in(twoIds!=null&&twoIds.size()>0, "id",twoIds)
                        .or()
                        .eq("id", oneId);
            itemCatMapper.delete(queryWrapper);
        }
    }

    /**
     * 将所有记录以 父级id: 商品分类 的map形式封装起来
     * @return
     */
    private Map<Integer, List<ItemCat>> getMap() {
        //查询所有状态为1的商品分类的记录
        QueryWrapper<ItemCat> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", "1");
        List<ItemCat> list = itemCatMapper.selectList(queryWrapper);
        //封装到map
        Map<Integer, List<ItemCat>> map = new HashMap<>();
        for (ItemCat itemCat:list){
            Integer parentId = itemCat.getParentId();
            if (map.containsKey(parentId)){
                map.get(parentId).add(itemCat);
            }else{
                List<ItemCat> tempList = new ArrayList<>();
                tempList.add(itemCat);
                map.put(parentId, tempList);
            }
        }
        return map;
    }

    /**
     * 获取2层菜单
     * @param map
     * @return
     */
    private List<ItemCat> getTwoList(Map<Integer, List<ItemCat>> map) {
        //获取一级菜单
        List<ItemCat> oneList = map.get(0);
        //遍历所有菜单
        for (ItemCat oneItemCat:oneList){
            Integer parentId = oneItemCat.getId();
            List<ItemCat> twoList = map.get(parentId);
            oneItemCat.setChildren(twoList);
        }
        return oneList;
    }

    /**
     * 获取3层菜单
     * @param map
     * @return
     */
    private List<ItemCat> getThreeList(Map<Integer, List<ItemCat>> map) {
        //获取1,2级菜单
        List<ItemCat> oneList = getTwoList(map);
        //遍历集合获取二级数据
        for (ItemCat oneItemCat:oneList){
            List<ItemCat> twoList = oneItemCat.getChildren();
            //判空
            if (twoList==null||twoList.size()==0){
                continue;
            }
            for (ItemCat twoItemCat:twoList){
                Integer parentId = twoItemCat.getId();
                List<ItemCat> threeList = map.get(parentId);
                twoItemCat.setChildren(threeList);
            }
        }
        return oneList;
    }
}
